<?php

namespace app\api\model\cps;



use app\admin\model\Bg;
use app\api\model\ExtendConsume;
use app\api\model\Qrcode;
use app\api\model\UserConsumeLog;
use app\common\model\User;
use app\shopapi\model\ExtendConsumeShop;
use extend\Poster as PosterExtend;
use fast\Http;
use Msmm\MtMtz\Client;
use Msmm\MtMtz\Requests\ApiGetReferralLinkRequest;
use Msmm\MtMtz\Requests\ApiQueryCouponRequest;
use Msmm\MtMtz\Requests\ApiQueryOrderRequest;
use think\Request;

require_once ROOT_PATH.'extend/mtmtz-main/src/Client.php';
require_once ROOT_PATH.'extend/mtmtz-main/src/Requests/ApiQueryCouponRequest.php';
require_once ROOT_PATH.'extend/mtmtz-main/src/Requests/ApiGetReferralLinkRequest.php';
require_once ROOT_PATH.'extend/mtmtz-main/src/Requests/ApiQueryOrderRequest.php';
require_once ROOT_PATH.'extend/Poster.php';

class Mt
{

    protected $weapp_appkey = 'c0a4a69b7033f7d97f6f16b9e8b63f5e';

    protected $secret = '32fd5175f92d46b9aed59d86dab3b61d';

    protected $secret_2 = '8e8d52acaea2318d162d7f327062fe78';

    protected $apikey = 'dL4aXkyMfQIqylX3zDMP46Vxd3efJj4g';

    //商品查询接口
    public function queryCoupon ($page,$longitude,$latitude,$listTopiId,$sortField,$ascDescOrder,$platform,$bizLine,$user_id){

        $client = new Client();
        $client->setAppKey($this->weapp_appkey);
        $client->setSecret($this->secret);

        $request = new ApiQueryCouponRequest();

        $request->setPageNo($page);
        if ($longitude){
            $request->setLongitude($longitude);
        }
        if ($latitude){
            $request->setLatitude($latitude);
        }
        if ($listTopiId){
            $request->setListTopiId($listTopiId);
        }
        if ($sortField){
            $request->setSortField($sortField);
        }
        if ($ascDescOrder){
            $request->setAscDescOrder($ascDescOrder);
        }
        if ($platform){
            $request->setPlatform($platform);
        }
        if ($bizLine){
            $request->setBizLine($bizLine);
        }

        $res =  $client->execute($request);
        //dump($res);die;
        if ($res['code']==0){
            $data = $res['data'];
            foreach ($data as $k=>$v){
                $user = User::get($user_id);
                if ($platform==1){
                    if ($user->level==1||$user->level==2){
                        $rate = 0.2;
                    } elseif($user->level==3) {
                        $rate = 0.68;
                    }

                } else {
                    $rate = 0.56;
                }
                $data[$k]['commissionInfo']['wawa_commission'] = round($v['commissionInfo']['commission']*$rate,2);
                if (isset($v['deliverablePoiInfo']['deliveryDistance'])){
                    $data[$k]['deliverablePoiInfo']['deliveryDistance'] = round($v['deliverablePoiInfo']['deliveryDistance']/1000,2).'k';
                }

            }
            return $data;
        } else {
            throw new \Exception($res['message']);
        }

    }


    //转链接
    public function getlink($linkType,$skuViewId,$platform,$user_id)
    {
        $client = new Client();
        $client->setAppKey($this->weapp_appkey);
        $client->setSecret($this->secret);

        $request = new ApiGetReferralLinkRequest();

        $request->setLinkType($linkType);

        $request->setSkuViewId($skuViewId);

        $request->setPlatform($platform);

        $request->setSid($user_id);

        $res =  $client->execute($request);
        if ($res['code']==0){
            return $res['data'];
        } else {
            throw new \Exception($res['message']);
        }

    }

    //查询未结算的订单
    public function unliquidated()
    {
        $lists = UserConsumeLog::where(['cps_type'=>3,'consume_type'=>2,'is_to_account'=>0,'is_refund'=>0])
            ->field('pay_time,user_id')->order('pay_time asc')->find();
        if ($lists){
            $start = $lists['pay_time']-86400;
            $end = $lists['pay_time'];
            $this->queryorder(1,$lists['user_id'],1,$start,$end);
            $this->queryorder(2,$lists['user_id'],1,$start,$end);
        }
        //dump($lists);die;
        /*foreach ($lists as $k=>$v){
            $start = $v['pay_time']-600;
            $end = $v['pay_time'];
            $this->queryorder(1,$v['user_id'],1,$start,$end);
            $this->queryorder(2,$v['user_id'],1,$start,$end);
        }*/

    }


    //订单查询
    public function queryorder($platform,$user_id=0,$type=0,$start='',$end='')
    {
        $client = new Client();
        $client->setAppKey($this->weapp_appkey);
        $client->setSecret($this->secret);

        //$todayStartTimestamp = 1729674997-1800;
        //$todayEndTimestamp = 1729674997;

        $todayStartTimestamp = strtotime("today");

        $todayEndTimestamp = strtotime("tomorrow") - 1;

        if ($type==1){
            $todayStartTimestamp = $start;
            $todayEndTimestamp = $end;
        }

        $request = Request::instance();
        $domain=$request->domain();

        $request = new ApiQueryOrderRequest();
        //$request->setScrollId(1);
        $request->setStartTime($todayStartTimestamp);

        $request->setEndTime($todayEndTimestamp);

        $request->setPlatform($platform);
        if ($user_id)$request->setSid($user_id);

        $res =  $client->execute($request);

        if ($res['code']==0){
            $order_list = $res['data'];
            foreach ($order_list['dataList'] as $k=>$v){
                //增加消费记录
                $user = User::get($v['sid']);
                if ($user){
                    if ($platform==1){
                        if ($user->level==1||$user->level==2){
                            $commission = $v['profit']*0.2;
                        } elseif($user->level==3) {
                            $commission = $v['profit']*0.68;
                        }

                    } else {
                        $commission = $v['profit']*0.56;
                    }
                    $consume_log_info = UserConsumeLog::get([ 'user_id'=>$v['sid'], 'order_no'=>$v['orderId'],'consume_type'=>2, 'cps_type'=>3]);
                    if (!$consume_log_info){
                        $consume_log_model = new UserConsumeLog();
                        $consume_log_data = [
                            'user_id'=>$v['sid'],
                            'title'=>$v['productName'],
                            'shop_id'=>0,
                            'shop_name'=>'美团',
                            'image'=>$domain.'/assets/img/mt.png',
                            'order_no'=>$v['orderId'],
                            'pay_time'=>$v['payTime'],
                            'pay_price'=>$v['payPrice'],
                            'consume_type'=>2,
                            'cps_type'=>3,
                            'goods_id'=>$v['productId']?$v['productId']:'',
                            'commission'=>$commission,
                            'total_commission'=>$v['profit'],
                            'order_status_name'=>'已付款'
                        ];
                        User::update(['is_buy'=>1],['id'=>$user->id]);
                        $user_model = new User();
                        $user_model->upgrade($user->id);
                        $consume_log_model->save($consume_log_data);
                        //计算推广收益
                        if ($platform==1){
                            UserConsumeLog::waimaiCouponConsumeCalculate($user->id,$consume_log_model->total_commission,$consume_log_model->consume_id);
                        } else {
                            UserConsumeLog::lockMemberConsumeCalculate($user->id,$consume_log_model->total_commission,$consume_log_model->consume_id,0);
                        }
                    } else {
                        if ($v['status']==6&&$consume_log_info->is_to_account==0){
                            //发放消费记录的收益
                            UserConsumeLog::sendCommission($consume_log_info->order_no);
                        } elseif($v['status']==4||$v['status']==5&&$consume_log_info->is_refund==0) {
                            $consume_log_info->commission = 0;
                            $consume_log_info->order_status_name = '退款成功';
                            $consume_log_info->is_refund = 1;
                            $consume_log_info->save();
                            ExtendConsume::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                            ExtendConsumeShop::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                        }
                    }
                }

            }
            return $order_list;
        } else {
            throw new \Exception($res['message']);
        }
    }

    //自助取链接口
    public function url($linkType,$user_id)
    {
        $client = new Client();
        $client->setAppKey($this->weapp_appkey);
        $client->setSecret($this->secret);

        $request = new ApiGetReferralLinkRequest();
        if ($linkType==1)$linkType=2;

        $request->setLinkType($linkType);

        $request->setActId(7);

        $request->setSid($user_id);

        $res =  $client->execute($request);
        if ($res['code']==0){
            return $res['data'];
        } else {
            throw new \Exception($res['message']);
        }
        /*$api = "https://openapi.meituan.com/api/generateLink";
        $data = [
            'appkey'=>$this->weapp_appkey,
            'actId'=>33,
            'shortLink'=>1,
            'sid'=>'waimai',
            'linkType'=>$linkType
        ];

        $sign = $this->genSign($data);
        $data['sign'] = $sign;

        $res = Http::sendRequest($api,$data,'get');

        $res = json_decode($res['msg'],true);

        if ($res['status']==0){
            return $res['data'];
        } else {
            throw new \Exception($res['des']);
        }*/
    }

    //小程序生成二维码
    public function miniCode($user_id)
    {
        $page = $this->url(1,$user_id);

        $qrcode_param = ['suid'=>$user_id];

        $qrcode_info = $this->getQrcode('h5', $page, $qrcode_param);

        if ($qrcode_info[ 'code' ] < 0) return $qrcode_info;

        $member_info = User::get($user_id);
        if (empty($member_info))throw new \Exception('未获取到会员信息');


        try {

            $poster = new PosterExtend(750, 1100);
            $option = [

                [
                    'action' => 'imageCopy', // 写入背景图片
                    'data' => [
                        ROOT_PATH.'public/assets/img/poster_bg/mt.png',
                        0,
                        0,
                        750,
                        1100,
                    ]
                ],
                [
                    'action' => 'imageCopy', // 写入二维码
                    'data' => [
                        $qrcode_info[ 'data' ][ 'path' ],
                        205,
                        720,
                        305,
                        305
                    ]
                ]
            ];

            $option_res = $poster->create($option);
            if (is_array($option_res)) return $option_res;

            $res = $option_res->jpeg('upload/poster/mt',  $user_id . '_' . 'h5');

            if ($res['code']==0){
                $request = Request::instance();
                $domain=$request->domain();

                return $domain.'/'.$res['data']['path'];
            } else {
                throw new \Exception($res['message']);
            }
            //return $res;

        }  catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

    }

    public function oldminiCode()
    {
        $api = "https://openapi.meituan.com/api/miniCode";

        $data = [
            'appkey'=>$this->weapp_appkey,
            'actId'=>7,
            'sid'=>'waimai',
        ];

        $sign = $this->genSign($data);
        $data['sign'] = $sign;

        $res = Http::sendRequest($api,$data,'get');

        $res = json_decode($res['msg'],true);

        if ($res['status']==0){
            return $res['data'];
        } else {
            throw new \Exception($res['des']);
        }
    }

    //外卖订单
    public function waimaiorder()
    {
        $api = "https://openapi.meituan.com/api/orderList";

        $todayStartTimestamp = strtotime("today");

        $todayEndTimestamp = strtotime("tomorrow") - 1;

        $data = [
            'appkey'=>$this->weapp_appkey,
            'actId'=>33,
            'ts'=>time(),
            'startTime'=>$todayStartTimestamp,
            'endTime'=>$todayEndTimestamp,
            'page'=>1,
            'limit'=>100
        ];

        $sign = $this->genSign($data);
        $data['sign'] = $sign;

        $res = Http::sendRequest($api,$data,'get');

        $res = json_decode($res['msg'],true);
        $order_list = $res['dataList'];
        //dump($res);die;
        foreach ($order_list as $k=>$v){
            //增加消费记录
            $user = User::get($v['sid']);
            if ($user){

                if ($user->level==1||$user->level==2){
                    $commission = $v['profit']*0.2;
                } elseif($user->level==3) {
                    $commission = $v['profit']*0.68;
                }

                $consume_log_info = UserConsumeLog::get([ 'user_id'=>$v['sid'], 'order_no'=>$v['orderid'],'consume_type'=>2, 'cps_type'=>3]);
                if (!$consume_log_info){
                    $consume_log_model = new UserConsumeLog();
                    $consume_log_data = [
                        'user_id'=>$v['sid'],
                        'title'=>$v['productName'],
                        'shop_id'=>$v['itemId'],
                        'shop_name'=>$v['smstitle'],
                        'image'=>'/assets/img/mt.png',
                        'order_no'=>$v['orderid'],
                        'pay_time'=>$v['paytime'],
                        'pay_price'=>$v['payprice'],
                        'consume_type'=>2,
                        'cps_type'=>3,
                        'goods_id'=>$v['productId'],
                        'commission'=>$commission,
                        'total_commission'=>$v['profit'],
                        'order_status_name'=>'已付款'
                    ];
                    User::update(['is_buy'=>1],['id'=>$user->id]);
                    $user_model = new User();
                    $user_model->upgrade($user->id);
                    $consume_log_model->save($consume_log_data);
                    //计算推广收益

                    UserConsumeLog::waimaiCouponConsumeCalculate($user->id,$consume_log_model->total_commission,$consume_log_model->consume_id);

                } else {
                    if ($v['status']==8&&$consume_log_info->is_to_account==0){
                        //发放消费记录的收益
                        UserConsumeLog::sendCommission($consume_log_info->order_no);
                    } elseif($v['status']==9&&$consume_log_info->is_refund==0) {
                        $consume_log_info->commission = 0;
                        $consume_log_info->order_status_name = '退款成功';
                        $consume_log_info->is_refund = 1;
                        $consume_log_info->save();
                        ExtendConsume::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                        ExtendConsumeShop::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                    }
                }
            }

        }
        return $order_list;
    }

    //酒店活动
    public function hotel($user_id,$act_id)
    {
        $api = "http://api.jutuike.com/union/act";

        $data = [
            'apikey'=>$this->apikey,
            'sid'=>$user_id,
            'act_id'=>$act_id,
        ];

        $res = Http::sendRequest($api,$data);

        $result = json_decode($res['msg'],true);
        if ($result['code']==1){
            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }
    }

    public function genSign($params)
    {
        unset($params["sign"]);
        ksort($params);
        $str = $this->secret_2; // $secret为分配的密钥
        foreach($params as $key => $value) {
            $str .= $key . $value;
        }
        $str .= $this->secret_2;
        $sign = md5($str);
        return $sign;
    }


    /**
     * 获取二维码
     * @param unknown $app_type 请求类型
     * @param unknown $page uniapp页面路径
     * @param unknown $qrcode_param 二维码携带参数
     * @param string $promotion_type 活动类型 null为无活动
     */
    private function getQrcode($app_type, $page, $qrcode_param)
    {
        $data = [
            'app_type' => $app_type,
            'type' => 'get',
            'data' => $qrcode_param,
            'page' => $page,
            'qrcode_path' => 'upload/qrcode/share',
            'qrcode_name' => 'mt' . '_' . $qrcode_param[ 'suid' ],
        ];
        $qrcode_model = new Qrcode();
        $res = $qrcode_model->createQrcode($data);
        return $res;
    }
}